package com.iwish.server.storage.DAO;

import java.util.List;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.iwish.server.storage.CacheManager;
import com.iwish.server.storage.MongoPool;
import com.iwish.server.storage.RedisPool;
import com.iwish.server.storage.util.ConfigHelper;
import com.iwish.server.storage.util.MiscHelper;
import com.mongodb.Mongo;

public class RedisDAO {
	static Logger logger = Logger.getLogger(RedisDAO.class);


	public static Object execute(String key,RedisCommand command) {
	
		Jedis jedis = null;
		Long nodeKey = CacheManager.getShardInfo(key.getBytes());
		 RedisPool pool = CacheManager.nodes.get(nodeKey);
		 int i = 0 ;
		 while(i<ConfigHelper.REDIS_RETRY){
		 try{
			 jedis =(Jedis)pool.getResource();
			 break;
			 }
		 	catch(Exception e){
		 		i = i+1;
		 		if(i>=ConfigHelper.REDIS_RETRY) throw new RuntimeException(MiscHelper.error("redis cache fatal error, stop retrying",0));
			 logger.error(pool.getAlisa()+" connect error,evict", e);
			 CacheManager.nodes.remove(nodeKey);
			 logger.info("cache hash treemap reduced to	"+CacheManager.nodes.size());
			 nodeKey = CacheManager.getShardInfo(key.getBytes());
			 pool =CacheManager.nodes.get(nodeKey);
		 }
		 }
		 Object rs = null;
		 try{
		  rs = command.run(key, jedis);
		 }finally{
		 pool.returnResource(jedis);
		 }
		 return rs;
		 
	}
}
